package com.cl.ks.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class TaskServiceUtil {

    @Value("${task-service.url:http://localhost:8088/task}")
    private String taskServiceUrl;

    public ResponseEntity<Object> executeTask( JSONObject param) {
        OkHttpClient httpClient = new OkHttpClient();
        final MediaType JSON_TYPE = MediaType.parse("application/json;charset=utf-8");
        RequestBody body = RequestBody.create(JSON_TYPE, param.toJSONString());
        Request request = new Request.Builder()
                .url(taskServiceUrl + "/taskList/executeTask")
                .post(body)
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            return ResponseEntity.ok(Objects.requireNonNull(response.body()).string());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok("任务已提交");
    }
    public ResponseEntity getProgress(Integer taskListId) {
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(taskServiceUrl+ "/taskList/getProgress?taskListId=" + taskListId)
                .get()
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            return ResponseEntity.ok(Objects.requireNonNull(response.body()).string());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok("error");
    }
    public ResponseEntity<Object> executeTaskList(Integer taskListId) {
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(taskServiceUrl+ "/taskList/executeTaskList?taskListId=" + taskListId)
                .get()
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            return ResponseEntity.ok(Objects.requireNonNull(response.body()).string());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok("任务已提交");
    }
}
